package com.tj.jinzao.activity;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.InputFilter;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tj.jinzao.R;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.callback.IFamilyView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.model.FamilyMember;
import com.tj.jinzao.presenter.FamilyPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.ChooseBottomDialog;
import com.tj.jinzao.widgets.MaxTextLengthFilter;
import com.tj.jinzao.widgets.RoundedImageView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;

/**
 * 家庭成员资料页面
 * Created by wjy on 2019/1/5.
 */
public class FamilyPersonInfoActivity extends BaseActivity implements IFamilyView<List<FamilyMember>> {

    @BindView(R.id.iv_head)
    RoundedImageView mHeadView;
    @BindView(R.id.et_name)
    EditText mNameView;
    @BindView(R.id.tv_birthday)
    TextView mBirthDayView;
    @BindView(R.id.tv_gender)
    TextView mGenderView;
    @BindView(R.id.tv_weight)
    TextView mWeightView;
    @BindView(R.id.tv_height)
    TextView mHeightView;
    @BindView(R.id.tv_health)
    EditText mHealthView;
    @BindView(R.id.et_contact)
    EditText mContactView;
    @BindView(R.id.tv_status)
    TextView mStatusView;
    @BindView(R.id.rl_status_layout)
    RelativeLayout rl_status_layout;

    private String mImagePath;
    private long mId;
    private FamilyMember mMember;

    private FamilyPresenter mPresenter;

    public static void start(Context context, long id) {
        context.startActivity(new Intent(context, FamilyPersonInfoActivity.class)
                .putExtra("id", id));
    }
    @OnClick(R.id.rl_status_layout)
    public void rl_status_layout(){
        Intent to=new Intent();
        to.putExtra("mStep",6);
        to.putExtra("mType",2);
        to.setClass(this,CompleteInfoActivity.class);
        startActivityForResult(to,101);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_family_detail;
    }


    @Override
    protected CharSequence getRightButtonText() {
        return "保存";
    }

    @Override
    protected void setupView() {
        super.setupView();
        mId = getIntent().getLongExtra("id", 0);
        mPresenter = new FamilyPresenter(this);
        if (mId != 0) {
            mPresenter.getFamilyMember(mId);
        } else {
            mMember = new FamilyMember();
        }
        mNameView.setFilters(new InputFilter[]{new MaxTextLengthFilter(12,FamilyPersonInfoActivity.this,"昵称限12字以内")});

    }

    private void bindData() {
        try {
            Glide.with(this).load(Constant.IMAGE_PREFIX + mMember.getImgurl()).into(mHeadView);
            mNameView.setText(mMember.getName());
            mNameView.setClickable(false);
            mStatusView.setText(mMember.getPhysicalConditions());
            mHealthView.setText(mMember.getFamilyHealth());
            mBirthDayView.setText(mMember.getBirthday());
            mGenderView.setText(mMember.getGender() == 0 ? "男" : "女");
            if (mMember.getWeight() != 0) mWeightView.setText(String.valueOf(mMember.getWeight()));
            if (mMember.getHeight() != 0) mHeightView.setText(String.valueOf(mMember.getHeight()));
            mContactView.setText(mMember.getRelationship());
        } catch (Exception e) {
        }
    }

    @OnClick(R.id.ll_head_layout)
    public void chooseHead() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @OnClick(R.id.rl_gender_layout)
    public void chooseGender() {
        ChooseBottomDialog dialog = new ChooseBottomDialog(this);
        List<String> genderList = new ArrayList();
        genderList.add("男");
        genderList.add("女");
        dialog.setData(genderList, null, null, mGenderView.getText().toString().trim(), null, null);
        dialog.setValueListener(new ChooseBottomDialog.OnWheelValueListener() {
            @Override
            public void onValueChanged(String select1, String select2, String select3) {
                mGenderView.setText(select1);
            }

            @Override
            public void onValueChanging(int selectIndex, int wheelIndex) {

            }
        });
        dialog.show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia localMedia : selectList) {
                        mImagePath = localMedia.isCompressed() ? localMedia.getCompressPath() : localMedia.getPath();
                        Glide.with(this).load(mImagePath).into(mHeadView);
                    }
                    break;

                case 101:
                    try {
                        String target=data.getStringExtra("contentTarget");
                        mStatusView.setText(target);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    break;
            }
        }
    }


    @OnClick(R.id.rl_birthday_layout)
    public void chooseBirthDay() {
        ChooseBottomDialog dialog = new ChooseBottomDialog(this);
        Calendar calendar = Calendar.getInstance();
        List<String> yearList = new ArrayList();
        for (int i = 1900; i <= calendar.get(Calendar.YEAR); i++) {
            yearList.add(String.valueOf(i));
        }
        List<String> monthList = new ArrayList();
        for (int i = 1; i < 13; i++) {
            monthList.add(String.valueOf(i));
        }
        List<String> dayList = new ArrayList();
        for (int i = 1; i < 32; i++) {
            dayList.add(String.valueOf(i));
        }
        dialog.setValueListener(new ChooseBottomDialog.OnWheelValueListener() {
            @Override
            public void onValueChanged(String select1, String select2, String select3) {
                mBirthDayView.setText(select1 + "-" + select2 + "-" + select3);
            }

            @Override
            public void onValueChanging(int selectIndex, int wheelIndex) {

            }
        });
        dialog.setData(yearList, monthList, dayList, "1980"
                , String.valueOf(calendar.get(Calendar.MONTH) + 1)
                , String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
        dialog.show();
    }

    @OnClick(R.id.rl_height_layout)
    public void chooseHeight() {
        ChooseBottomDialog dialog = new ChooseBottomDialog(this);
        List<String> heightList = new ArrayList();
        for (int i = 100; i < 250; i++) {
            heightList.add(String.valueOf(i));
        }
        String height = mHeightView.getText().toString().trim();

        dialog.setData(heightList, null, null, TextUtils.isEmpty(height) ? "160" : height, null, null);
        dialog.setValueListener(new ChooseBottomDialog.OnWheelValueListener() {
            @Override
            public void onValueChanged(String select1, String select2, String select3) {
                mHeightView.setText(select1);
            }

            @Override
            public void onValueChanging(int selectIndex, int wheelIndex) {

            }
        });
        dialog.show();
    }

    @OnClick(R.id.rl_weight_layout)
    public void chooseWeight() {
        ChooseBottomDialog dialog = new ChooseBottomDialog(this);
        List<String> weightList = new ArrayList();
        for (int i = 30; i < 100; i++) {
            weightList.add(String.valueOf(i));
        }
        String weight = mWeightView.getText().toString().trim();
        dialog.setData(weightList, null, null, TextUtils.isEmpty(weight) ? "160" : weight, null, null);
        dialog.setValueListener(new ChooseBottomDialog.OnWheelValueListener() {
            @Override
            public void onValueChanged(String select1, String select2, String select3) {
                mWeightView.setText(select1);
            }

            @Override
            public void onValueChanging(int selectIndex, int wheelIndex) {

            }
        });
        dialog.show();
    }

    @Override
    protected void clickRightButton() {
        upload();
    }

    private void upload() {
        Map<String, Object> map = new HashMap();
        if (!TextUtils.isEmpty(mImagePath)) {
            if (mImagePath.startsWith(Constant.SD_ROOT)) {
                mPresenter.uploadFile(mImagePath);
                return;
            }
            map.put("imgurl", mImagePath);
        }
        String nickName = mNameView.getText().toString().trim();
        if (!TextUtils.equals(nickName, mMember.getName())) {
            map.put("name", nickName);
        }
        String birthday = mBirthDayView.getText().toString().trim();
        if (!TextUtils.equals(birthday, mMember.getBirthday())) {
            map.put("birthday", birthday);
        }
        int gender = TextUtils.equals(mGenderView.getText().toString().trim(), "男") ? 0 : 1;
        if (gender != mMember.getGender()) {
            map.put("gender", gender);
        }
        int weight = Utils.parseInt(mWeightView.getText().toString().trim());
        if (weight != mMember.getWeight()) {
            map.put("weight", weight);
        }
        int height = Utils.parseInt(mHeightView.getText().toString().trim());
        if (weight != mMember.getHeight()) {
            map.put("height", height);
        }
        String relationship = mContactView.getText().toString().trim();
        if (!TextUtils.equals(relationship, mMember.getRelationship())) {
            map.put("relationship", relationship);
        }
        String mStatus = mStatusView.getText().toString().trim();
        if (!TextUtils.equals(mStatus, mMember.getPhysicalConditions())) {
            map.put("physicalConditions", mStatus);
        }
        String health = mHealthView.getText().toString().trim();
        if (!TextUtils.equals(health, mMember.getFamilyHealth())) {
            map.put("familyHealth", health);
        }

        if (map.size() > 0) {
            if (mId == 0) {
                if (TextUtils.isEmpty(mNameView.getText())) {
                    ToastUtils.showToast(this, "请输入姓名");
                    return;
                }
                mPresenter.addFamily(map);
            } else {
                mPresenter.updateFamily(mId, map);
            }
        } else {
            super.clickLeftButton();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(List<FamilyMember> familyMembers) {
        mMember = familyMembers.get(0);
        if(familyMembers.get(0).getType()==2){
            ToastUtils.showToast(FamilyPersonInfoActivity.this,"添加成员成功");
            finish();
        }if(familyMembers.get(0).getType()==3){
            ToastUtils.showToast(FamilyPersonInfoActivity.this,"成员信息更新成功");
            finish();
        }else {
            bindData();
        }

    }

    @OnClick(R.id.rl_health_layout)
    public void chooseHealth() {
//        startActivityForResult(new Intent(this, ));
    }

    @OnClick(R.id.rl_health_layout)
    public void chooseStatus() {
//        startActivityForResult(new Intent(this, ));
    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    public void onUploadSuccess(String path, String url) {
        mImagePath = url;
        upload();
    }




    @Override
    public void onAddFamily(FamilyMember member) {
        ToastUtils.showToast(this, mId == 0 ? "添加成功" : "更新成功");
        finish();
    }
}
